import 'dart:ffi';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mall/api/api.dart';
import 'package:mall/constant/string.dart';
import 'package:mall/entity/user_entity.dart';
import 'package:mall/event/login_event.dart';
import 'package:mall/model/user_info.dart';
import 'package:mall/service/user_service.dart';
import 'package:mall/utils/http_util.dart';
import 'package:mall/utils/shared_preferences_util.dart';
import 'package:mall/utils/toast_util.dart';
import 'package:provider/provider.dart';

class WeMoney extends StatefulWidget {
  const WeMoney({Key key}) : super(key: key);

  @override
  _WeMoneyState createState() => _WeMoneyState();
}

class _WeMoneyState extends State<WeMoney> {
  bool isLogin = false;
  var imageHeadUrl;
  var nickName;

  _getUserInfo() {
    SharedPreferencesUtils.getToken().then((token) {
      if (token != null) {
        setState(() {
          isLogin = true;
        });
        SharedPreferencesUtils.getImageHead().then((imageHeadAddress) {
          setState(() {
            imageHeadUrl = imageHeadAddress;
          });
        });
        SharedPreferencesUtils.getUserName().then((name) {
          setState(() {
            nickName = name;
          });
        });
      }
    });
  }

  void _getJifen() {
    SharedPreferencesUtils.getToken().then((token) async {
      Options options = Options(headers: {});
      options.headers["x-fltmall-token"] = token;
      String url = Api.BASE_URL + "/user/info";
      print(url);
      var response = await HttpUtil().get(
        Api.BASE_URL + "/user/info",
        options: options
      );
      print(response);
      // if (response['errno'] == 0) {
      // } else {}
    });
  }

  @override
  void initState() {
    super.initState();
    _getUserInfo();
    _getJifen();
  }

  Future _openAlertDialog(String jifen, String yue) async {
    final action = await showDialog(
      context: context,
      barrierDismissible: false, //// user must tap button!
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('提示'),
          content: Text('当前积分为${jifen},可以转换为余额${yue}'),
          actions: <Widget>[
            FlatButton(
              child: Text('取消'),
              onPressed: () {
                Navigator.pop(context, "取消");
              },
            ),
            FlatButton(
              child: Text('确认'),
              onPressed: () {
                Navigator.pop(context, "确认");
              },
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    UserEntity userEntity = context.read<UserInfoModel>().userEntity;
    return Scaffold(
      appBar: AppBar(
        title: Text("我的钱包"),
        centerTitle: true,
      ),
      body: ListView(
        children: [
          Container(
            padding: EdgeInsets.symmetric(vertical: 20),
            color: Colors.deepOrangeAccent,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Container(
                  width: ScreenUtil().setWidth(100),
                  height: ScreenUtil().setHeight(100),
                  margin: EdgeInsets.only(left: ScreenUtil().setWidth(30.0)),
                  child: CircleAvatar(
                    radius: ScreenUtil().setWidth(50),
                    foregroundColor: Colors.deepOrangeAccent,
                    backgroundImage: NetworkImage(
                      imageHeadUrl ?? "",
                    ),
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(left: ScreenUtil().setWidth(10.0)),
                ),
                Text(
                  nickName ?? "",
                  style: TextStyle(
                      fontSize: ScreenUtil().setSp(26.0), color: Colors.white),
                ),
              ],
            ),
          ),
          Container(
            padding: EdgeInsets.symmetric(horizontal: 20, vertical: 20),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Column(
                  children: [
                    Text("积分",
                        style: TextStyle(
                            fontSize: 30, fontWeight: FontWeight.bold)),
                    SizedBox(height: 10),
                    Text("1000", style: TextStyle(fontSize: 20)),
                  ],
                ),
                Column(
                  children: [
                    Text("余额",
                        style: TextStyle(
                            fontSize: 30, fontWeight: FontWeight.bold)),
                    SizedBox(height: 10),
                    Text("1000(元)", style: TextStyle(fontSize: 20)),
                  ],
                )
              ],
            ),
          ),
          Divider(),
          Container(
            margin: EdgeInsets.only(top: 20),
            padding: EdgeInsets.symmetric(horizontal: 40),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                InkWell(
                  onTap: () {
                    _openAlertDialog("1000", "100");
                  },
                  child: Column(
                    children: [
                      Icon(Icons.account_balance_wallet,
                          color: Colors.red, size: 50),
                      new Text("积分转余额"),
                    ],
                  ),
                ),
                InkWell(
                  onTap: () {
                    Navigator.push(context,
                        MaterialPageRoute(builder: (context) => TiXianList()));
                  },
                  child: Column(
                    children: [
                      Icon(Icons.account_tree_sharp,
                          color: Colors.red, size: 50),
                      new Text("余额提现"),
                    ],
                  ),
                )
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 50),
            padding: EdgeInsets.symmetric(horizontal: 40),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                InkWell(
                  onTap: () {
                    Navigator.push(context,
                        MaterialPageRoute(builder: (context) => BindWechat()));
                  },
                  child: Column(
                    children: [
                      Icon(Icons.filter_vintage, color: Colors.green, size: 50),
                      new Text("设置"),
                    ],
                  ),
                ),
                InkResponse(
                  onTap: () {
                    Navigator.push(context,
                        MaterialPageRoute(builder: (context) => Mingxi()));
                  },
                  child: Column(
                    children: [
                      Icon(Icons.assignment_outlined,
                          color: Colors.red, size: 50),
                      new Text("账务明细"),
                    ],
                  ),
                )
              ],
            ),
          ),
          Divider(),
        ],
      ),
    );
  }
}

class Mingxi extends StatefulWidget {
  const Mingxi({Key key}) : super(key: key);

  @override
  _MingxiState createState() => _MingxiState();
}

class _MingxiState extends State<Mingxi> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("账务明细"),
        centerTitle: true,
      ),
      body: ListView.builder(
          itemCount: 20,
          itemBuilder: (BuildContext context, int index) {
            return Container(
              decoration: BoxDecoration(
                  border: Border(bottom: BorderSide(color: Colors.grey))),
              padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Icon(Icons.assignment_outlined,
                          color: Colors.red, size: 30),
                      SizedBox(width: 10),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          new Text("提现"),
                          new Text("2021-11-09 10:28:04",
                              style:
                                  TextStyle(fontSize: 16, color: Colors.grey))
                        ],
                      ),
                    ],
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      new Text("-21.87"),
                      new Text("交易成功",
                          style: TextStyle(fontSize: 16, color: Colors.grey))
                    ],
                  ),
                ],
              ),
            );
          }),
    );
  }
}

class TiXianList extends StatefulWidget {
  const TiXianList({Key key}) : super(key: key);

  @override
  _TiXianListState createState() => _TiXianListState();
}

class _TiXianListState extends State<TiXianList> {
  List<double> moneyList = [0.5, 24, 123];

  int currentIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey.shade300,
      appBar: AppBar(
        title: Text("体现"),
        centerTitle: true,
      ),
      bottomNavigationBar: SafeArea(
        child: Container(
          height: 50,
          alignment: Alignment.center,
          color: Colors.deepOrangeAccent,
          child: new Text("确认提现",
              style: TextStyle(fontSize: 20, color: Colors.white)),
        ),
      ),
      body: Column(
        children: [
          Container(
            padding: EdgeInsets.symmetric(vertical: 20, horizontal: 20),
            color: Colors.white,
            child: Column(
              children: [
                Row(
                  children: [
                    new Text("你已经绑定账号", style: TextStyle(fontSize: 20)),
                  ],
                ),
                SizedBox(height: 20),
                Row(
                  children: [
                    new Text(
                      "昵称：雷奥科技",
                      style: TextStyle(fontSize: 20),
                    ),
                  ],
                )
              ],
            ),
          ),
          SizedBox(height: 20),
          Container(
            color: Colors.white,
            padding: EdgeInsets.symmetric(horizontal: 10, vertical: 4),
            child: Row(
              children: [
                new Text("金额（元）", style: TextStyle(fontSize: 20)),
                SizedBox(width: 20),
                new Text("当前账号余额9.98",
                    style: TextStyle(fontSize: 16, color: Colors.grey))
              ],
            ),
          ),
          SizedBox(height: 20),
          Container(
            color: Colors.white,
            padding: EdgeInsets.symmetric(horizontal: 4, vertical: 10),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: moneyList
                  .asMap()
                  .keys
                  .map((e) => InkResponse(
                        onTap: () {
                          setState(() {
                            currentIndex = e;
                          });
                        },
                        child: Container(
                          padding:
                              EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                          decoration: BoxDecoration(
                              border: Border.all(
                                  color: currentIndex == e
                                      ? Colors.red
                                      : Colors.grey)),
                          child: Row(
                            children: [
                              new Text("提现", style: TextStyle(fontSize: 16)),
                              new Text("${moneyList[e]}元",
                                  style: TextStyle(
                                      fontSize: 16, color: Colors.red))
                            ],
                          ),
                        ),
                      ))
                  .toList(),
            ),
          ),
          SizedBox(height: 10),
          Row(
            children: [
              SizedBox(width: 20),
              new Text("预计", style: TextStyle(fontSize: 16)),
              new Text("次日中午12点",
                  style: TextStyle(fontSize: 16, color: Colors.red)),
              new Text("前到账", style: TextStyle(fontSize: 16)),
            ],
          )
        ],
      ),
    );
  }
}

class BindWechat extends StatefulWidget {
  const BindWechat({Key key}) : super(key: key);

  @override
  _BindWechatState createState() => _BindWechatState();
}

class _BindWechatState extends State<BindWechat> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("设置"),
          centerTitle: true,
        ),
        body: Container(
          child: Column(
            children: [
              Container(
                decoration: BoxDecoration(
                    border: Border(bottom: BorderSide(color: Colors.black12))),
                padding: EdgeInsets.symmetric(horizontal: 20, vertical: 20),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    new Text("绑定微信", style: TextStyle(fontSize: 20)),
                    Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        new Text("去绑定"),
                        Icon(Icons.arrow_right),
                      ],
                    )
                  ],
                ),
              ),
              Divider()
            ],
          ),
        ));
  }
}
